package sdk

import (
	"context"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"likeadmin/util"
	"mime/multipart"
	"path"
)

var QiniuKodo = qiniuKodo{}

type qiniuKodo struct{}

func (q qiniuKodo) Upload(file *multipart.FileHeader, key string, folder string) (err error) {
	conf := util.SettingUtil.GetStorageEngineConf("qiniu")
	bucket := conf.Bucket
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(conf.AccessKey, conf.SecretKey)
	upToken := putPolicy.UploadToken(mac)

	cfg := storage.Config{
		// 是否使用https域名进行资源管理
		UseHTTPS: true,
	}
	resumeUploader := storage.NewResumeUploaderV2(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.RputV2Extra{}

	objectName := path.Join(folder, key)

	// 读取文件流
	src, err := file.Open()
	if err != nil {
		return
	}
	defer src.Close()

	err = resumeUploader.Put(context.Background(), &ret, upToken, objectName, src, file.Size, &putExtra)
	return
}

func (q qiniuKodo) Delete(objectName string) (err error) {
	conf := util.SettingUtil.GetStorageEngineConf("qiniu")
	bucket := conf.Bucket

	mac := qbox.NewMac(conf.AccessKey, conf.SecretKey)

	cfg := storage.Config{
		// 是否使用https域名进行资源管理
		UseHTTPS: true,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	err = bucketManager.Delete(bucket, objectName)

	return
}
